package com.bangwz.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Client {

	private Selector selector;

	private ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

	public static void main(String[] args) throws IOException {
		Client c = new Client().init("127.0.0.1", 9527);
		c.listen();
	}

	/**
	 * 连接器
	 * 
	 * @param server
	 * @param port
	 * @throws IOException
	 */
	public Client init(String server, int port) throws IOException {

		// 管理器
		selector = Selector.open();

		// 获取socket通道
		SocketChannel channel = SocketChannel.open();
		// 设置非阻塞
		channel.configureBlocking(false);
		SocketAddress SocketAddress = new InetSocketAddress(server, port);

		// client conn server,需要调用channel.finishCon才算真正的连上了
		channel.connect(SocketAddress);

		// 为该通道注册SelectionKey.OP_CONNECT事件
		SelectionKey key = channel.register(selector, SelectionKey.OP_CONNECT);

		// 连接完成
		if (channel.finishConnect()) {
			System.out.println("client connect opended...");
			key.interestOps(SelectionKey.OP_READ);
		} else {
			// connect is failed
			return null;
		}
		ByteBuffer src = ByteBuffer.wrap("我已经连接上服务器.".getBytes());
		channel.write(src);
		return this;
	}

	public void listen() throws IOException {
		while (true) {
			int select = selector.select();
			// 没有就绪的
			if (select == 0)
				continue;
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			while (iterator.hasNext()) {
				SelectionKey key = iterator.next();
				// 得到通道
				SocketChannel channel = (SocketChannel) key.channel();

				// 可读事件
				if (key.isReadable()) {
					channel.read(byteBuffer);
					byte[] array = byteBuffer.array();
					System.out.println("收到服务器消息：" + new String(array));
					byteBuffer.clear();
					channel.write(ByteBuffer.wrap("收到服务器消息.".getBytes()));
				}
				// // 可写事件
				// if (key.isWritable()) {
				//
				// }
				iterator.remove();
			}
		}
	}

}
